﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GO_Test_1.Components;
using GO_Test_1.Tools;
using Microsoft.Xna.Framework;

namespace GO_Test_1 {

	public static class CollisionHelper {

		public static Movement? ReflectBallOffWalls(Rectangle ball, Movement ballMovement, Rectangle container) {
			if ((ball.Top < container.Top && ballMovement.Direction.Y < 0) || (ball.Bottom > container.Bottom && ballMovement.Direction.Y > 0)) {
				ballMovement.Direction = new Vector2(ballMovement.Direction.X, ballMovement.Direction.Y*-1);
				return ballMovement;
			}
			if ((ball.Right > container.Right && ballMovement.Direction.X > 0) || (ball.Left < container.Left && ballMovement.Direction.X < 0)) {
				ballMovement.Direction = new Vector2(ballMovement.Direction.X*-1, ballMovement.Direction.Y);
				return ballMovement;
			}
			return null;
		}

		public static Movement ReflectBall(Rectangle ball, Movement movement, Rectangle block) {
			// Get info on how deep the overlap is on x and y and on which sides.
			Vector2 collisionInfo = ball.GetIntersectionDepth(block);

			// Back the ball out by the shallowest intersection depth, then test it's position against the target rectangle.
			// If it hit a corner straight on, they will be the same.
			Vector2 positionCorrection;
			if (Math.Abs(collisionInfo.X) < Math.Abs(collisionInfo.Y)) {
				positionCorrection = new Vector2(collisionInfo.X, collisionInfo.X*movement.Direction.X/movement.Direction.Y);
			} else if (Math.Abs(collisionInfo.Y) < Math.Abs(collisionInfo.X)) {
				positionCorrection = new Vector2(collisionInfo.Y*movement.Direction.Y/movement.Direction.X, collisionInfo.Y);
			} else {
				positionCorrection = new Vector2(collisionInfo.X, collisionInfo.Y);
			}
			ball.Location = new Point(ball.Location.X+(int) positionCorrection.X, ball.Location.Y+(int) positionCorrection.Y);

			// Determine reflections.
			bool reflectX = false;
			bool reflectY = false;
			if ((ball.Right == block.Left && ball.Bottom == block.Top) || (ball.Left == block.Right && ball.Bottom == block.Top) || (ball.Left == block.Right && ball.Top == block.Bottom) || (ball.Right == block.Left && ball.Top == block.Bottom)) {
				reflectX = true;
				reflectY = true;
			} else if (ball.Left == block.Right || ball.Right == block.Left) {
				reflectX = true;
			} else if (ball.Top == block.Bottom || ball.Bottom == block.Top) {
				reflectY = true;
			}

			// Apply reflections.
			if (reflectX) {
				movement.Direction = new Vector2(movement.Direction.X*-1, movement.Direction.Y);
			}
			if (reflectY) {
				movement.Direction = new Vector2(movement.Direction.X, movement.Direction.Y*-1);
			}
			return movement;
		}

	}

}